package com.gzz.core.util;

import com.gzz.core.toolkit.ParamMap;
import org.lionsoul.ip2region.DataBlock;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbMakerConfigException;
import org.lionsoul.ip2region.DbSearcher;
import org.springframework.core.io.ClassPathResource;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Iterator;
import java.util.Map;

/**
 *
 */
public class RequestUtil {
    /**
     * @param request
     * @return
     */
    public static ParamMap toParamMap(HttpServletRequest request) {
        // 返回值Map
        ParamMap returnMap = new ParamMap();
        Iterator entries = request.getParameterMap().entrySet().iterator();
        Map.Entry entry;
        String name = "";
        String value = "";
        while (entries.hasNext()) {
            entry = (Map.Entry) entries.next();
            name = (String) entry.getKey();
            Object valueObj = entry.getValue();
            if (null == valueObj) {
                value = "";
            } else if (valueObj instanceof String[]) {
                String[] values = (String[]) valueObj;
                for (int i = 0; i < values.length; i++) {
                    value = values[i] + ",";
                }
                value = value.substring(0, value.length() - 1);
            } else {
                value = valueObj.toString();
            }
            returnMap.put(name, value);
        }
        return returnMap;
    }

    /**
     * 获取客户端IP
     * @param request
     * @return
     */
    public static String getRemoteIpAddr(HttpServletRequest request){
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            if("127.0.0.1".equals(ip)||"0:0:0:0:0:0:0:1".equals(ip)){
                //根据网卡取本机配置的IP
                InetAddress inet=null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ip= inet.getHostAddress();
            }
        }
        //对于通过多个代理的情况，第一个IP为福为客户端的真实IP
        if(ip  !=null && ip.length()>15){
            ip = ip.split(",")[0];
        }
        return ip;
    }

    /**
     * 查询IP所在区域
     * @param ip
     * @return
     */
    public static String getIPRegion(String ip){
        try {
            File tmpFile = new ClassPathResource("").getFile();// 数据库文件流
        } catch (IOException e) {
            e.printStackTrace();
        }
        String dbPath = RequestUtil.class.getResource("ip2region.db").getPath();
        File file = new File(dbPath);
        if (file.exists() == false){
            System.out.println("Error: Invalid ip2region.db file");
        }
        // 定义查询算法
        //int  algorihm = DbSearcher.BTREE_ALGORITHM;
        try {
            DbConfig config =new DbConfig();
            DbSearcher searcher = new DbSearcher(config, dbPath);
            DataBlock block = searcher.btreeSearch(ip);
            return block.getRegion();
        } catch (DbMakerConfigException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //
        return null;
    }
}
